package cn.uncode.springcloud.starter.canary.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ObjectUtils;

import cn.uncode.springcloud.starter.canary.api.CanaryContext;
import cn.uncode.springcloud.starter.canary.api.CanaryStrategy;
import cn.uncode.springcloud.starter.canary.api.DefaultCanaryContext;
import cn.uncode.springcloud.starter.canary.api.DefaultCanaryStrategy;
import cn.uncode.springcloud.starter.canary.feign.FeignCanaryInterceptor;
import cn.uncode.springcloud.starter.canary.properties.CanaryProperties;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;



/**
 * 
 * @author juny
 * @date 2019年1月18日
 * <pre>
 * 使用说明：
 * 1、配置节点灰度标识：eureka.instance.metadata-map.canary=dev
 * 
 * </pre>
 *
 */
@Data
@Slf4j
@Configuration
@EnableConfigurationProperties({CanaryProperties.class})
@ConditionalOnProperty(value = "info.canary.enabled", havingValue = "true")
public class CanaryStrategyAutoConfiguration {
	
	@Autowired
	private CanaryProperties canaryProperties;
	
	@Autowired(required = false)
	private CanaryStrategy canaryStrategy;
	
	@Bean
    @ConditionalOnMissingBean
    public CanaryContext canaryContext() {
		if(ObjectUtils.isEmpty(canaryStrategy)) {
			canaryStrategy = new DefaultCanaryStrategy(canaryProperties);
		}
		CanaryContext canaryContext = new DefaultCanaryContext(canaryStrategy);
		log.info("===Uncode-starter===CanaryStrategyAutoConfiguration===>CanaryContext inited...");
        return canaryContext;
    }
	
	@Bean
	public FeignCanaryInterceptor feignCanaryInterceptor() {
		log.info("===Uncode-starter===CanaryStrategyAutoConfiguration===>FeignCanaryInterceptor inited...");
		return new FeignCanaryInterceptor();
	}

}
